package edu.uwosh.cs342.group5;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.concurrent.ExecutionException;

import org.json.JSONException;
import org.json.JSONObject;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

import edu.uwosh.cs342.group5.Route.*;
import edu.uwosh.cs342.group5.async.AsyncMethod;
import edu.uwosh.cs342.group5.async.AsyncRoute;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;


public class GoogleMapsPJ4Activity extends MapActivity {
	private MapController mapController;
	private MapView mapView;
	private LocationManager locationManager;
	private MapOverlay itemizedoverlay;
	private RouteOverlay overlay;
	private MyLocationOverlay myLocationOverlay;
	private Road mRoad;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        mapView = (MapView) findViewById(R.id.mapview);
		mapView.setBuiltInZoomControls(true);
		mapController = mapView.getController();
		mapController.setZoom(14);
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
				0, new GeoUpdateHandler());

		myLocationOverlay = new MyLocationOverlay(this, mapView);
		mapView.getOverlays().add(myLocationOverlay);

		myLocationOverlay.runOnFirstFix(new Runnable() {
			public void run() {
				mapView.getController().animateTo(
						myLocationOverlay.getMyLocation());
			}
		});
		
		SharedPreferences app_preferences = PreferenceManager
				.getDefaultSharedPreferences(this);
		
		SharedPreferences.Editor editor = app_preferences.edit();
		
		if(app_preferences.contains("directionsOn") && app_preferences.getBoolean("directionsOn", false)) {
			drawDirections();
		}
		Drawable drawable = this.getResources().getDrawable(R.drawable.point);
		itemizedoverlay = new MapOverlay(this, drawable);
		createMarker();
		
//		GetJSONObject task = new GetJSONObject();
//		task.execute("5538 Jacqueline Dr. West Bend, WI 53095");
//		try {
//			JSONObject point = task.get();
//			if (point != JSONObject.NULL) {
//				setMarker(point);
//				setMarker(point);
//			}
//		} catch (InterruptedException e) {
//			e.printStackTrace();
//		} catch (ExecutionException e) {
//			e.printStackTrace();
//		}
    }
    
    private void createMarker() {
		GeoPoint p = mapView.getMapCenter();
		OverlayItem overlayitem = new OverlayItem(p, "", "");
		itemizedoverlay.addOverlay(overlayitem);
		if (itemizedoverlay.size() > 0) {
			mapView.getOverlays().add(itemizedoverlay);
		}
	}
    
    public boolean onCreateOptionsMenu(Menu menu){
    	super.onCreateOptionsMenu(menu);
    	MenuInflater inflater = getMenuInflater();
    	inflater.inflate(R.menu.menu, menu);
    	return true;
    }
    
    public boolean onOptionsItemSelected(MenuItem item){
    	switch (item.getItemId()) {
    	case R.id.directions:
    		Route go = new Route();
    		//get current gps
    		double curLon = -89.045818;
    		double curLat = 43.385346;
    		//get destination gps
    		double destLon = -88.5516930;
    		double destLat = 44.0241130;
    		String url = go.getURL(curLat, curLon, destLat, destLon);
    		//get Connection
    		AsyncMethod<Route> rte = new AsyncMethod<Route>(Route.class, go, "getConnection");
    		rte.execute(url);
    		InputStream is = (InputStream)rte.getResult();
    		//get the Route
    		AsyncRoute ar = (AsyncRoute) new AsyncRoute().execute(is);
    		try {
				mRoad = (Road) ar.get();
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (ExecutionException e) {
				e.printStackTrace();
			}

    		overlay = new RouteOverlay(mRoad, mapView);
    		List<Overlay> list = mapView.getOverlays();
    		list.add(overlay);
    		mapView.invalidate();
    		break;
    	}
    	return true;
    }
    
    public void drawDirections() {
    	Route go = new Route();
    	LocationManager loc = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    			
		//get current gps
		double curLon = loc.getLastKnownLocation(LOCATION_SERVICE).getLongitude();
		double curLat = loc.getLastKnownLocation(LOCATION_SERVICE).getLatitude();
		
		SharedPreferences app_preferences = PreferenceManager
				.getDefaultSharedPreferences(this);
		
		SharedPreferences.Editor editor = app_preferences.edit();
		//get destination gps
		double destLon = app_preferences.getFloat("lng", 0);
		double destLat = app_preferences.getFloat("lat", 0);
		String url = go.getURL(curLat, curLon, destLat, destLon);
		//get Connection
		AsyncMethod<Route> rte = new AsyncMethod<Route>(Route.class, go, "getConnection");
		rte.execute(url);
		InputStream is = (InputStream)rte.getResult();
		//get the Route
		AsyncRoute ar = (AsyncRoute) new AsyncRoute().execute(is);
		try {
			mRoad = (Road) ar.get();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}

		overlay = new RouteOverlay(mRoad, mapView);
		List<Overlay> list = mapView.getOverlays();
		list.add(overlay);
		mapView.invalidate();
		
	
    }

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}
	
	void setMarker(JSONObject json) {
		GeoPoint p= null;
		try {
			p = new GeoPoint((int) (json.getJSONArray("results").getJSONObject(0).getJSONObject("geometry").getJSONObject("location").getDouble("lat")*1E6), 
					(int) (json.getJSONArray("results").getJSONObject(0).getJSONObject("geometry").getJSONObject("location").getDouble("lng")*1E6));
			System.out.println(json.getJSONArray("results").getJSONObject(0).getJSONObject("geometry").getJSONObject("location").getDouble("lng")*1E6);
			mapController.animateTo(p);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		OverlayItem overlayitem = new OverlayItem(p, "", "");
		itemizedoverlay.addOverlay(overlayitem);
		if (itemizedoverlay.size() > 0) {
			mapView.getOverlays().add(itemizedoverlay);
		}
	}
	
	public class GeoUpdateHandler implements LocationListener {
		String key = "AIzaSyDbk0g7U1-LBUTGliNJI5jxbRnLhGlnxkw";
		String ref = "CoQBeAAAABoPbVgl2GAo6QSsxtVGyRnl7yQ4TRiP6eVx5BXFDE9HHtVzTxygHlsqkrfY01fIwdKeG7SWVt4Midrpnq885AEGsEwmOI_2XTn4GDlc6Rfmq2SBxqXPO9r6-WPcQzvskvlUynLXNOb_40eobnLD1aWk3W4p_Rqhgj5_cvcGGkEOEhB6RNY1Ux46x8UGqK4YCFnEGhTYeU19eeVGaw6N4qrNHrW31Ys2VQ";


//		@Override
		public void onLocationChanged(Location location) {
			int lat = (int) (location.getLatitude() * 1E6);
			int lng = (int) (location.getLongitude() * 1E6);
			
			new AsyncPlaces(key, location.getLatitude(), location.getLongitude(), false, 1000).execute();
			new AsyncPlaceDetails(key, ref, false, GoogleMapsPJ4Activity.this).execute();
			
			GeoPoint point = new GeoPoint(lat, lng);
			createMarker();
			mapController.animateTo(point); // mapController.setCenter(point);

		}

		public void onProviderDisabled(String provider) {
		}

		public void onProviderEnabled(String provider) {
		}

		public void onStatusChanged(String provider, int status, Bundle extras) {
		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		myLocationOverlay.enableMyLocation();
		myLocationOverlay.enableCompass();
	}

	@Override
	protected void onPause() {
		super.onResume();
		myLocationOverlay.disableMyLocation();
		myLocationOverlay.disableCompass();
	}
	
	private class GetJSONObject extends AsyncTask<String, Void, JSONObject> {

		@Override
		protected JSONObject doInBackground(String... arg0) {
			URL url = null;
			JSONObject returnVal=null;
			
			//String urlString = arg0[0];
			
			String urlString = "http://maps.googleapis.com/maps/api/geocode/json?sensor=true&address=";
			//while(arg0[0].contains(" ")) {
			arg0[0] = arg0[0].replace(' ', '+');
			while(arg0[0].contains("++")) {
				arg0[0] = arg0[0].replace("++", "+");
			}
			try {
				url = new URL(urlString+arg0[0]);
			}
			catch(MalformedURLException e) {
				e.printStackTrace();
			}
			HttpURLConnection conn;
			try {
				conn = (HttpURLConnection)url.openConnection();
			
				HttpURLConnection.setFollowRedirects(false);
				conn.setConnectTimeout(5000);
				BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
				String next = "";
				String JSONValue="";
				while((next = in.readLine()) != null) {
					JSONValue += next +"\n";
				}
				returnVal = new JSONObject(JSONValue);
				System.out.println(JSONValue);
				
			} catch (Exception e) {
				e.printStackTrace();
			}
			//}
			
			return returnVal;
		}
		
	}
}